<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      width="60%"
      :title="getTitle"
      @ok="handleSubmit"
      destroyOnClose
    >
      <BasicForm @register="registerForm">
        <template #areaSlot>
          <Space>
            <Select
              v-model:value="province"
              placeholder="请选择"
              style="max-width: 458px; min-width: 176px"
              :options="provinceData.map((pro) => ({ value: pro }))"
              @change="handleChangeProvince"
            />
            <Select
              v-model:value="secondCity"
              placeholder="请选择"
              style="max-width: 458px; min-width: 176px"
              :options="cities.map((city) => ({ value: city }))"
              @change="handleChangeCity"
            />
          </Space>
        </template>
        <template #coverUrlSlot="{ model, field }">
          <Spin :spinning="spinning">
            <Upload
              v-model:file-list="fileList"
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :action="uploadImgApi"
              :before-upload="beforeUpload"
              @change="handleChange(field)"
            >
              <img v-if="model[field]" :src="model[field]" alt="avatar" />
              <div v-else>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </Upload>
          </Spin>
          <div class="hint">建议图片尺寸：宽750*高440rpx</div>
        </template>
        <template #buttonSlot>
          <a-button type="primary" style="margin-left: 200px" @click="handleAddHouseType">
            添加房型
          </a-button>
        </template>
        <template #deleteAreaSpec="{ field }">
          <a-button danger @click="handleDeleteAreaSpec(field)"> 删除房型 </a-button>
        </template>
        <template #sq="{ model, field }">
          <Input placeholder="请输入" v-model:value="model[field]">
            <template #addonAfter>
              <div style="width: 60px">sq.ft</div>
            </template>
          </Input>
        </template>
        <template #rentPay="{ model, field }">
          <Input placeholder="请输入" v-model:value="model[field]">
            <template #addonAfter>
              <Select
                v-model:value="value1"
                style="width: 80px"
                placeholder="请选择"
                :options="type.map((pro) => ({ value: pro }))"
              />
            </template>
          </Input>
        </template>
        <template #floorplaUrlSlot="{ model, field }">
          <Spin :spinning="spinning">
            <Upload
              v-model:file-list="floorFileList"
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :action="uploadImgApi"
              :before-upload="beforeUpload"
              @change="handleChange(field)"
            >
              <img v-if="model[field]" :src="model[field]" alt="avatar" />
              <div v-else>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </Upload>
          </Spin>
          <div class="hint">建议图片尺寸：宽750*高440rpx</div>
        </template>
      </BasicForm>
    </BasicModal>
  </div>
</template>

<script lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { buildingFormSchema } from './buildingManage.data';
  import { computed, defineComponent, ref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Input, Spin, Upload, Space, Select } from 'ant-design-vue';

  const provinceData = [
    'Zhejiang',
    'Jiangsu',
    'ZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiang',
  ];
  const cityData = {
    Zhejiang: ['Hangzhou', 'Ningbo', 'Wenzhou'],
    Jiangsu: ['Nanjing', 'Suzhou', 'Zhenjiang'],
    ZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiang: [
      'ZhejiangZhejiangZhejiangZhejiangZhejiangZhejZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangiangZhejiangZhejiangZhejiang',
      'ZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiangZhejiang',
    ],
  };
  const type = ['$/月', '￥/月'];

  const formData = [
    {
      label: ' ',
      field: 'deleteAreaSpec',
      component: 'Input',
      colProps: { span: 12 },
      slot: 'deleteAreaSpec',
    },
    {
      label: '添加Floorplan',
      field: 'floorplaUrl',
      component: 'Upload',
      colProps: { span: 12 },
      slot: 'floorplaUrlSlot',
    },
    {
      field: 'rentPay',
      label: '租金',
      component: 'Input',
      colProps: { span: 12 },
      slot: 'rentPay',
    },
    {
      field: 'rentTime',
      label: '租期',
      component: 'Select',
      colProps: { span: 12 },
      defaultValue: '12个月及以上',
      componentProps: {
        placeholder: '请选择',
        options: [
          { label: '12个月及以上', value: '12个月及以上' },
          { label: '6个月及以上', value: '6个月及以上' },
        ],
      },
    },
    {
      field: 'sq',
      label: '面积',
      component: 'Input',
      colProps: { span: 12 },
      slot: 'sq',
    },
    {
      field: 'houseType',
      label: '房型',
      component: 'Select',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请选择',
        options: [
          { label: '房型一', value: '房型一' },
          { label: '房型二', value: '房型二' },
        ],
      },
    },
  ];

  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      Spin,
      Upload,
      Space,
      Select,
      Input,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const getTitle = ref('');
      const isUpdate = ref(false);
      const spinning = ref(false);
      const fileList = ref<any[]>([]);
      const floorFileList = ref<any[]>([]);
      const province = ref(provinceData[0]);
      const secondCity = ref(cityData[province.value][0]);
      const uploadImgApi = () => {};
      const showAddHouseType = ref(false);
      const value1 = ref<string>('$/月');
      const insertFields = ref<any[]>([]);
      const count = ref(0);
      const area = ref('');

      const cities = computed(() => {
        return cityData[province.value];
      });

      // 表单
      const [
        registerForm,
        { setFieldsValue, resetFields, validate, appendSchemaByField, removeSchemaByFiled },
      ] = useForm({
        labelWidth: 200,
        schemas: buildingFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      // 模态框
      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = data.isUpdate;
        if (data.isUpdate) {
          getTitle.value = '编辑大楼';
          setFieldsValue({
            ...data.record,
          });
        } else {
          getTitle.value = '新增大楼';
        }
      });

      // 表单提交
      const handleSubmit = async () => {
        try {
          // 表单校验
          const values = await validate();
          // 开启确定按钮的加载状态
          setModalProps({ confirmLoading: true });
          const { createMessage } = useMessage();
          values.hoseType = insertFields.value;
          console.log(values);

          if (isUpdate.value) {
            // 编辑
            createMessage.success('编辑成功');
          } else {
            // 新增
            createMessage.success('新增成功');
          }
          emit('success');
          closeModal();
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };

      // 上传前
      const beforeUpload = () => {
        console.log('beforeUpload');
      };

      const handleChange = (field) => {
        console.log('handleChange');
        const obj = {};
        obj[field] = 'pic-url';
        setFieldsValue(obj);
      };

      // 添加房型
      const handleAddHouseType = () => {
        showAddHouseType.value = true;
        const centerArr: any[] = [];
        const cloneData = JSON.parse(JSON.stringify(formData));
        cloneData.forEach((item: any) => {
          item.field = item.field + '-' + count.value;
          appendSchemaByField(item, 'insert');
          centerArr.push({ field: item.field });
        });
        insertFields.value.push(centerArr);
        count.value++;
        console.log(insertFields.value);
      };

      // 删除房型
      const handleDeleteAreaSpec = (field) => {
        const index = field.split('-')[1];
        let Index = -1;
        insertFields.value.forEach((item: any, i) => {
          if (item[0].field.indexOf(index) !== -1) {
            Index = i;
          }
        });
        insertFields.value[Index].forEach((item: any) => {
          removeSchemaByFiled(item.field);
        });
        insertFields.value.splice(Index, 1);
        console.log(insertFields.value);
      };

      // 选择省
      const handleChangeProvince = (e) => {
        area.value = e;
        setFieldsValue({ area: area.value });
      };

      // 选择城市
      const handleChangeCity = (e) => {
        area.value = area.value + '/' + e;
        setFieldsValue({ area: area.value });
      };

      return {
        province,
        secondCity,
        getTitle,
        registerForm,
        registerModal,
        handleSubmit,
        spinning,
        fileList,
        floorFileList,
        uploadImgApi,
        beforeUpload,
        handleChange,
        provinceData,
        cityData,
        cities,
        handleAddHouseType,
        showAddHouseType,
        value1,
        type,
        handleDeleteAreaSpec,
        handleChangeProvince,
        handleChangeCity,
      };
    },
  });
</script>

<style scoped lang=""></style>
